import { Swipeout, SwipeoutItem, SwipeoutButton,Confirm } from 'vux'
import AddReduceBtn from '../../components/add-reduce-btn.vue'
import Raven from 'raven-js';

export default {
  name:"Cart",
  components: {
    Swipeout,
    SwipeoutItem,
    SwipeoutButton,
    Confirm,
    AddReduceBtn
  },
  data(){
    return {
      isAllCheck:true,//是否全选
      isEdit:false,
      cartInfo:{},
      cartList:[],
      account:0,
      show:false,//是否删除弹框提示
      confirmData:{
        show:false,
        title:'',
        onConfirm:function () {

        }
      },
      sellerId:'',//店铺id
      shopInfo:{}
    }
  },
  beforeRouteLeave(to, from, next) {//记录离开时的位置
    let currentPosition = this.$refs.cart_scroller && this.$refs.cart_scroller.getPosition() && this.$refs.cart_scroller.getPosition().top;
    sessionStorage.cartContentP = currentPosition?currentPosition:0;
    next()
  },
  methods:{
    yasuo(img){
      return img.indexOf('?')==-1?img+"?yasuo":img;
    },
    onCancel () {
      // console.log('on cancel')
    },
    commit(){
      let ids=this.getSelectIds();
      if(ids.length<=0){
        this.$vux.toast.text("请选择商品", 'middle');
        return;
      }
      let flag1=false;let flag2=false;
      if(this.cartInfo.shoppingCartVOList){
        for(let i=0;i<this.cartInfo.shoppingCartVOList.length;i++){
          if(this.cartInfo.shoppingCartVOList[i].checked&&this.cartInfo.shoppingCartVOList[i].goodsVO.state==1&&this.cartInfo.shoppingCartVOList[i].goodsVO.goodsState==1&&this.cartInfo.shoppingCartVOList[i].goodsVO.enquiry==0){
            if((this.cartInfo.shoppingCartVOList[i].stockFlag&&this.cartInfo.shoppingCartVOList[i].num>this.cartInfo.shoppingCartVOList[i].goodsStock)||this.cartInfo.shoppingCartVOList[i].sameGoodsStock==1){
              flag1=true;
            }
            if(this.cartInfo.shoppingCartVOList[i].goodsVO.enquiry==1){
              flag1=true;
            }
          }
        }
      }

      this.initData()

      if(flag1&&!flag2){
        this.$vux.toast.text("存在库存不足的商品，请联系商家", 'middle');
        return;
      }
      if(!flag1&&flag2){
        this.$vux.toast.text("存在询价的商品，请联系商家", 'middle');
        return;
      }

      if(flag1&&flag2){
        this.$vux.toast.text("存在库存不足和询价的商品，请联系商家", 'middle');
        return;
      }


      if(this.$fromApp(this)){
        // this.$callJava({url:this.$webUrl+"cart/confirm?from=app&ids="+ids.join(',')+"&sellerId="+this.sellerId})
        this.$router.push({ path:'/cart/confirm',query:{ids:ids.join(','),sellerId:this.sellerId,from:'app'}})
      }else{
        this.$router.push({ path:'/cart/confirm',query:{ids:ids.join(','),sellerId:this.sellerId}})
      }
    },
    editInit(){
      // if(process.env.NODE_ENV!=="development") {
      //   try {
      //     this.car()
      //   } catch (e) {
      //     Raven.captureException(e)
      //   }
      // }
      this.isEdit=!this.isEdit;
    },
    change(val){
      this.countNum()
    },
    onDel(good){

      let _this=this;
      this.$vux.confirm.show({
        title: '',
        content: '确定要删除该商品吗？',
        onCancel () {},
        onConfirm () {
          _this.$ajax.post('replenish/shopping_cart/setting',{goodsId:good.goodsId,unitId:good.unitId,num:0},(res)=>{
            // console.log("删除单个商品",res)
            if(res.code==200){
              for(let i=0;i<_this.cartInfo.shoppingCartVOList.length;i++){
                if(_this.cartInfo.shoppingCartVOList[i].id==good.id){
                  _this.cartInfo.shoppingCartVOList.splice(i,1)
                  _this.countNum()
                  _this.$root.eventHub.$emit('updateCart')
                }
              }
            }
          })
        }
      })
    },
    goDetail(item){
      // console.log(item)
      if(item.goodsVO.state==0||item.goodsVO.goodsState==0){
        this.$vux.toast.text("商品已下架", 'middle');
        return;
      }
      if(this.$fromApp(this)){
       // this.$callJava({url:this.$webUrl+"good/operate?from=app&id="+item.goodsId})
        this.$router.push({path:"/good/operate",query:{goodId:item.goodsId,from:'app'}})
      }else{
        this.$router.push({path:"/good/operate",query:{goodId:item.goodsId}})
      }
    },
    //清除下架商品请求
    deleteDownGood(){
      let _this=this;
      this.$vux.confirm.show({
        title: '',
        content: '确定要清理下架的商品吗？',
        onCancel () {},
        onConfirm () {
          _this.$ajax.get('replenish/shopping_cart/delete_off',(res)=>{
            // console.log("确定要清理下架的商品吗",res)
            _this.$root.eventHub.$emit('updateCart')
            _this.initData()
          },{sellerId:_this.sellerId})
        }
      })
    },
    getSelectIds(){
      let ids=[];
      if(this.cartInfo.shoppingCartVOList){
        for(let i=0;i<this.cartInfo.shoppingCartVOList.length;i++){
          if(this.cartInfo.shoppingCartVOList[i].checked&&this.cartInfo.shoppingCartVOList[i].goodsVO.state==1&&this.cartInfo.shoppingCartVOList[i].goodsVO.goodsState==1){  //&&this.cartInfo.shoppingCartVOList[i].goodsVO.enquiry==0
            ids.push(this.cartInfo.shoppingCartVOList[i].id)
          }
        }
      }
      return ids;
    },
    deleteCheckGood(){
      let _this=this;
      let ids=this.getSelectIds();
      // console.log(ids)
      if(ids.length<=0){
        this.$vux.toast.text("请选择要删除的商品", 'middle');
        return;
      }
      this.$vux.confirm.show({
        title: '',
        content: '确定要删除这些商品吗？',
        onCancel () {},
        onConfirm () {
          _this.$ajax.get('replenish/shopping_cart/delete',(res)=>{
            // console.log("确定要删除这些商品吗",res)
            _this.initData()
            _this.$root.eventHub.$emit('updateCart')
          },{ids:ids.join(',')})
        }
      })
    },

    updateStock(obj){
      let num=0;
      if(this.cartInfo&&this.cartInfo.shoppingCartVOList){
        for(let i=0;i<this.cartInfo.shoppingCartVOList.length;i++){
          if(this.cartInfo.shoppingCartVOList[i].goodsId==obj.good.goodsId){
            num+=this.cartInfo.shoppingCartVOList[i].num*this.cartInfo.shoppingCartVOList[i].unitRate
          }
        }

        for(let i=0;i<this.cartInfo.shoppingCartVOList.length;i++){
          if(this.cartInfo.shoppingCartVOList[i].goodsId==obj.good.goodsId){

            console.log(this.cartInfo.shoppingCartVOList[i],this.shopInfo)
            if(this.shopInfo.zeroSaleFlag==1||this.cartInfo.shoppingCartVOList[i].goodsVO.zeroSaleFlag==1){
              if(obj.good.goodsVO.goodsStock<num&&this.cartInfo.shoppingCartVOList[i].unitRate==1){
                console.log("11111")
                this.$set(this.cartInfo.shoppingCartVOList[i],'sameGoodsStock',1)
              }else if(obj.good.goodsVO.goodsStock==num){
                console.log("2222")
                this.$set(this.cartInfo.shoppingCartVOList[i],'sameGoodsStock',2)
              }else{
                console.log("000")
                this.$set(this.cartInfo.shoppingCartVOList[i],'sameGoodsStock',0)
              }
              this.$set(this.cartInfo.shoppingCartVOList, i, this.cartInfo.shoppingCartVOList[i])
            }
          }
        }
      }
    },

    //计算合计
    countNum(param){  //主要判断商品是否选中已经在售
      // console.log("param",param)
      if(param&&param.data==4){
        this.initData()
      }
      let val=0;
      if(this.cartInfo&&this.cartInfo.shoppingCartVOList){
        for(let i=0;i<this.cartInfo.shoppingCartVOList.length;i++){
          if(this.cartInfo.shoppingCartVOList[i].checked&&this.cartInfo.shoppingCartVOList[i].goodsVO.state==1&&this.cartInfo.shoppingCartVOList[i].goodsVO.goodsState==1&&this.cartInfo.shoppingCartVOList[i].goodsVO.enquiry==0){
            val+=this.cartInfo.shoppingCartVOList[i].num*this.cartInfo.shoppingCartVOList[i].currentPrice
          }
        }
      }
      this.account=val.toFixed(2);
      console.log("--------------",this.account)
      // this.initData();
      this.fullRule()
    },

    //改变商品选中状态
    setGoodCheck(good){
      // console.log(good)
      let flag=true;
      for(let i=0;i<this.cartInfo.shoppingCartVOList.length;i++){
        if(!this.cartInfo.shoppingCartVOList[i].checked&&this.cartInfo.shoppingCartVOList[i].goodsVO.state!=0&&this.cartInfo.shoppingCartVOList[i].goodsVO.goodsState!=0){
          flag=false;
        }
      }
      this.isAllCheck=flag;
      this.countNum()
    },

    //全选按钮
    setAllCheckBt(){
      // console.log(this.isAllCheck)
      this.setAllCheck(this.isAllCheck)
    },
    //改变全选状态
    setAllCheck(flag){
      if(this.cartInfo.shoppingCartVOList){
        for(let i=0;i<this.cartInfo.shoppingCartVOList.length;i++){
          this.cartInfo.shoppingCartVOList[i].checked=flag;
        }
      }
      this.cartInfo=JSON.parse(JSON.stringify(this.cartInfo));
      this.countNum()
    },

    fullRule(){
      //计算满赠规则
      if(this.cartInfo.shoppingCartVOList&&this.cartInfo.shoppingCartVOList.length>0){
        for(let i=0;i<this.cartInfo.shoppingCartVOList.length;i++){
          if(this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods){
            let minFullFlag=false;//是否满足最低规则
            for(let j=0;j<this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO.length;j++){
              let giftInfo={
                brandName:this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO[j].brandName,
                goodsName:this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO[j].goodsName,
                normalGoodsPrice:this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO[j].normalGoodsPrice,
                unitName:this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO[j].unitName
              }

              if(this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO[j].giveRule==0){
                if(this.cartInfo.shoppingCartVOList[i].num>=this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO[j].num) {
                  giftInfo.giftNum = this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO[j].giftNum
                  this.cartInfo.shoppingCartVOList[i].giftInfo = giftInfo
                }else{
                  this.cartInfo.shoppingCartVOList[i].giftInfo=null
                }

              }else{
                if(this.cartInfo.shoppingCartVOList[i].num>=this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO[j].num){
                  minFullFlag=true;
                  giftInfo.giftNum=this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO[j].giftNum
                  if(j==(this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO.length-1)){
                    //判断是否超过最高
                    console.log('---====',j)
                    // giftInfo.giftNum=
                    giftInfo.giftNum=Math.floor(this.cartInfo.shoppingCartVOList[i].num/this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO[j].num)*this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO[j].giftNum
                  }
                  this.cartInfo.shoppingCartVOList[i].giftInfo=giftInfo
                }else{
                  if(j==(this.cartInfo.shoppingCartVOList[i].currentFullGiftActivityGoods.activityFullRuleVO.length-1)&&!minFullFlag){
                    this.cartInfo.shoppingCartVOList[i].giftInfo=null
                  }
                }
              }
            }
          }
        }
      }

      //存在相同商品时候判断库存

    },
    getScroll(){

      if(sessionStorage.cartContentP){
        setTimeout(() => {
          this.$refs.cart_scroller.scrollTo(0,sessionStorage.cartContentP , false);
        }, 50)
      }


    },
    initData(){
      //获取经销商信息
      this.$ajax.get('common/distributor/info',res2=>{
        if(res2.code == '200'){
          console.log('经销商信息：',res2)
          this.shopInfo = res2.data;

          this.$ajax.get("replenish/shopping_cart/info",(res) => {
            console.log(res)
            if(res.code==200){
              if(res.data&&res.data.shoppingCartVOList){

                //判断是否库提示库存不足
                let flag=true;
                for(let i=0;i<res.data.shoppingCartVOList.length;i++){
                  if(res2.data.zeroSaleFlag==0&&res.data.shoppingCartVOList[i].goodsVO.zeroSaleFlag==0){
                    res.data.shoppingCartVOList[i].stockFlag=false;
                    res.data.shoppingCartVOList[i].checked=true;
                  }else{
                    res.data.shoppingCartVOList[i].stockFlag=true
                    if(res.data.shoppingCartVOList[i].goodsVO.goodsStock<res.data.shoppingCartVOList[i].num){
                      res.data.shoppingCartVOList[i].checked=false;
                      flag=false;
                    }else{
                      if(res.data.shoppingCartVOList[i].sameGoodsTotalNum>res.data.shoppingCartVOList[i].goodsVO.goodsStock&&res.data.shoppingCartVOList[i].unitRate==1){
                        res.data.shoppingCartVOList[i].sameGoodsStock=1;
                        res.data.shoppingCartVOList[i].checked=false;
                      }else{
                        res.data.shoppingCartVOList[i].checked=true;
                      }

                    }
                  }

                }

                this.getScroll();

                console.log(res.data)

                this.cartInfo=res.data
                this.setGoodDown();
                this.isAllCheck=flag
                this.countNum()
              }else{
                this.cartInfo=res.data
                this.countNum()
                this.isAllCheck=false
              }
            }else{
            }
          },{sellerId:this.sellerId});
        }
      },{distributorId:this.sellerId});


    },
    androidCallJs (str) {

    },
    //把下架的商品置到底部
    setGoodDown(){
      let goodsList=[]
      if(this.cartInfo.shoppingCartVOList.length>0){
        for(let i=0;i<this.cartInfo.shoppingCartVOList.length;i++){
          if(this.cartInfo.shoppingCartVOList[i].goodsVO.goodsState==1&&this.cartInfo.shoppingCartVOList[i].goodsVO.state==1){
            goodsList.push(this.cartInfo.shoppingCartVOList[i])
          }
        }
        for(let i=0;i<this.cartInfo.shoppingCartVOList.length;i++){
          if(this.cartInfo.shoppingCartVOList[i].goodsVO.goodsState==0||this.cartInfo.shoppingCartVOList[i].goodsVO.state==0){
            goodsList.push(this.cartInfo.shoppingCartVOList[i])
          }
        }
        this.cartInfo.shoppingCartVOList=goodsList;
      }
    },
    goHomePage() {
      // this.$callJava({ code: 1007 });
      // this.$router.go(-1)
      this.$router.replace({
        path: "/purchase/storePage",
        query: {
          id: this.$route.query.id
            ? this.$route.query.id
            : this.$route.query.sellerId,
          from: this.$fromApp(this) ? "app" : ''
        }
      });
    },
  },
  created:function(){
    window['androidCallJs'] =this.androidCallJs;
    this.sellerId = this.$route.query.id;
    this.initData()
  },
  mounted:function(){
    this.$storage.remove('address')
    this.$callJava({ onBackPressed: true });
    this.oldOnBackPressed = window["onBackPressed"]
    window["onBackPressed"] = this.goHomePage.bind(this);
  },
  destroyed() {
    window["onBackPressed"] = this.oldOnBackPressed;
    this.$callJava({ onBackPressed: false });
  },
}
